import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: () => import('@/views/admin/AdminLogin.vue'),
    meta: {
      requiresAuth: false,
      title: '管理员登录'
    }
  },
  {
    path: '/admin',
    name: 'AdminLayout',
    component: () => import('@/views/admin/AdminLayout.vue'),
    redirect: '/admin/dashboard',
    meta: {
      requiresAuth: true,
      title: '管理后台'
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/AdminDashboard.vue'),
        meta: {
          requiresAuth: true,
          title: '仪表盘'
        }
      },
      {
        path: 'posts',
        name: 'Posts',
        component: () => import('@/views/admin/AdminPosts.vue'),
        meta: {
          requiresAuth: true,
          title: '文章管理'
        }
      },
      {
        path: 'photos',
        name: 'Photos',
        component: () => import('@/views/admin/AdminPhoto.vue'),
        meta: {
          requiresAuth: true,
          title: '图片管理'
        }
      },
      {
        path: 'comments',
        name: 'Comments',
        component: () => import('@/views/admin/AdminComments.vue'),
        meta: {
          requiresAuth: true,
          title: '评论管理'
        }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/admin/AdminUsers.vue'),
        meta: {
          requiresAuth: true,
          title: '用户管理'
        }
      },
  
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/admin/AdminInfo.vue'),
        meta: {
          requiresAuth: true,
          title: '个人资料'
        }
      },
      {
        path: 'info',
        name: 'AdminInfo',
        component: () => import('@/views/admin/AdminInfo.vue'),
        meta: {
          requiresAuth: true,
          title: '管理员信息'
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/admin/login'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫，处理登录验证
router.beforeEach((to, from, next) => {
  // 获取token
  const isLoggedIn = localStorage.getItem('adminToken')
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 管理系统`
  }
  
  // 判断页面是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录权限但未登录，跳转到登录页
    if (!isLoggedIn) {
      next({ 
        path: '/admin/login',
        query: { redirect: to.fullPath } // 保存原本要访问的路径，便于登录后跳转
      })
    } else {
      next() // 已登录，放行
    }
  } else {
    // 不需要登录权限的页面
    if (to.path === '/admin/login' && isLoggedIn) {
      // 已登录状态下访问登录页，重定向到首页
      next({ path: '/admin/dashboard' })
    } else {
      next() // 放行
    }
  }
})

// const submitChangePwd = () => {
//   pwdFormRef.value.validate(async (valid) => {
//     if (!valid) return
//     try {
//       await request.post('http://localhost:8081/admin/change-password', {
//         old_password: pwdForm.value.old_password,
//         new_password: pwdForm.value.new_password
//       })
//       ElMessage.success('密码修改成功，请重新登录')
//       changePwdDialogVisible.value = false
//       // 可选：强制退出登录
//       await request.post('/admin/logout')
//       localStorage.removeItem('token')
//       router.push('/admin/login')
//     } catch (error) {
//       ElMessage.error(error?.response?.data?.msg || '密码修改失败')
//     }
//   })
// }

export default router 